<!-- <template>
  <view class="submitorder-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
      <view class="navbar-title">提交订单</view>
      <view class="navbar-right">
        <u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
        <u-icon name="minus" size="20" color="#333" @click="minimize"></u-icon>
        <u-icon name="target" size="20" color="#333" @click="showTarget"></u-icon>
      </view>
    </view>



    <!-- 地址选择 -->
    <view class="address-section" @click="selectAddress">
      <view class="address-content">
        <view class="address-left">
          <u-icon name="map-pin" size="24" color="#ff4444"></u-icon>
          <view class="address-info">
            <view class="address-text">{{addressInfo.username}} {{addressInfo.address}}</view>
            <view class="phone-text">{{addressInfo.phone}}</view>
          </view>
        </view>
        <view class="address-right">
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-section">
      <view class="shop-info">
        <u-icon name="shopping-cart" size="16" color="#333"></u-icon>
        <text class="shop-name">{{productInfo.shopName}}</text>
      </view>
      
      <view class="product-item">
        <image class="product-image" :src="productInfo.image" mode="aspectFill"></image>
        <view class="product-info">
          <view class="product-name">{{productInfo.name}}</view>
          <view class="product-specs" v-if="productInfo.specs">{{productInfo.specs}}</view>
          <view class="product-quantity">数量:{{productInfo.quantity}}</view>
          <view class="product-price">¥ {{productInfo.price}}</view>
        </view>
      </view>
      
      <!-- 订单选项 -->
      <view class="order-options">
        <view class="option-item" @click="selectDeliveryService">
          <text class="option-label">配送服务</text>
          <view class="option-right">
            <text class="option-value">{{deliveryService}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item">
          <text class="option-label">配送费用</text>
          <view class="option-right">
            <text class="option-value">¥ {{deliveryFee}}</text>
          </view>
        </view>
        
        <view class="option-item" @click="selectStoreCoupon">
          <text class="option-label">店铺优惠券</text>
          <view class="option-right">
            <text class="option-value coupon-value">- ¥ {{storeCoupon}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item" @click="addOrderNote">
          <text class="option-label">订单备注</text>
          <view class="option-right">
            <text class="option-value">{{orderNote || '选填'}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item" @click="selectInvoice">
          <text class="option-label">开具发票</text>
          <view class="option-right">
            <text class="option-value">{{invoiceText}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格明细 -->
    <view class="price-section">
      <view class="section-title">价格明细</view>
      
      <view class="price-item">
        <text class="price-label">平台优惠券</text>
        <view class="price-right">
          <text class="price-value coupon-value">-¥{{platformCoupon}}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">积分抵扣</text>
        <view class="price-right">
          <u-checkbox 
            v-model="usePoints" 
            @change="togglePoints"
            shape="circle"
            size="20"
          ></u-checkbox>
          <text class="points-text">{{usePoints ? '使用积分抵扣' : '不使用积分抵扣'}}</text>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">商品总价</text>
        <view class="price-right">
          <text class="price-value">¥{{totalProductPrice}}</text>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">店铺优惠</text>
        <view class="price-right">
          <text class="price-value coupon-value">-¥{{storeDiscount}}</text>
        </view>
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="footer-bar">
      <view class="footer-left">
        <view class="total-info">
          共{{totalQuantity}}件 合计:¥<text class="total-price">{{totalAmount}}</text>
        </view>
        <view class="discount-info">共优惠 ¥{{totalDiscount}}元</view>
      </view>
      <view class="footer-right">
        <u-button 
          type="primary" 
          size="large" 
          @click="submitOrder"
          :loading="submitting"
        >提交订单</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserId } from '../../utils/auth.js';
import {get,post,del,put} from '../../utils/request.js';
import { getAddressById, getDefaultAddress, formatAddress } from '../../utils/addressApi.js';
export default {
  name: 'SubmitOrder',
  data() {
    return {
      submitting: false,
      usePoints: false,
      addressInfo: {
        address: '',
        phone: '',
        username: ''
      },
      productInfo: {
        shopName: 'Mall4j蓝海商城',
        name: '',
        quantity: 0,
        price: '0.00',
        image: '',
        specs: ''
      },
      deliveryService: '快递配送',
      deliveryFee: '0.00',
      storeCoupon: '0.00',
      orderNote: '',
      invoiceText: '本次不开具发票',
      platformCoupon: '0.00',
      totalProductPrice: '0.00',
      storeDiscount: '0.00',
      totalQuantity: 0,
      totalAmount: '0.00',
      totalDiscount: '0.00',
	  userId: Number(getUserId()), // 用户ID，如果获取失败则默认为1
      // 新增订单数据字段
      orderData: null
    }
  },
  async onLoad(options) {
    console.log('订单提交页面加载，接收参数:', options);
    
    // 添加地址变化事件监听
    uni.$on('addressChanged', this.onAddressChanged);
    
    try {
      // 初始化页面数据（包括地址信息）
      await this.initPageData(options);
      
      // 如果没有商品参数，则尝试加载现有订单数据
      if (!options.productId) {
        this.find();
      }
    } catch (error) {
      console.error('页面初始化失败:', error);
      // 如果初始化失败，至少加载默认地址
      this.loadDefaultAddress();
    }
  },
  
  onShow() {
    // 页面显示时刷新地址信息，确保地址列表页面的更改能够同步
    this.refreshAddressInfo();
  },
  
  onUnload() {
    // 移除事件监听器，避免内存泄漏
    uni.$off('addressChanged', this.onAddressChanged);
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 跳转到登录页
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    },
	async find(){
		try {
		    const res = await get('/orderst/list',{});
		    if (res && res.code === 200) {
		      // 检查数据结构，优先使用 res.data，如果没有则使用 res.rows
		      let orderData = res.data || res.rows || [];
		      
		      if (Array.isArray(orderData) && orderData.length > 0) {
		        let submitorder = orderData[0];
		        console.log('获取到订单数据:', submitorder);
		        
		        // 更新地址信息
		        this.addressInfo.address = submitorder.useraddress || '';
		        this.addressInfo.username = submitorder.username || '';
		        this.addressInfo.phone = submitorder.userphone || '';
		        
		        // 更新商品信息
		        this.productInfo.name = submitorder.goodsname || '';
		        this.productInfo.image = submitorder.goodsimg || '';
		        this.productInfo.specs = submitorder.goodsSpecs || '';
		        this.productInfo.quantity = parseInt(submitorder.goodsnumber) || 0;
		        this.productInfo.price = submitorder.goodsprice || '0.00';
		        
		        // 更新订单信息
		        this.orderNote = submitorder.orderComment || '';
		        this.totalProductPrice = (parseFloat(submitorder.goodsprice || 0) * parseInt(submitorder.goodsnumber || 0)).toFixed(2);
		        this.deliveryFee = (parseFloat(submitorder.orderPostPrice || 0)).toFixed(2);
		        this.totalQuantity = parseInt(submitorder.goodsnumber) || 0;
		        
		        // 计算总金额和优惠
		        this.calculateTotal();
		        
		        // 保存完整订单数据
		        this.orderData = submitorder;
		        
		        console.log('订单数据加载成功:', submitorder);
		      } else {
		        console.warn('没有找到订单数据');
		        // 如果没有订单数据，可以设置一些默认值
		        this.loadDefaultAddress();
		      }
		    }
		  } catch (error) {
		    console.error('获取订单列表失败:', error);
		    uni.showToast({
		      title: '获取订单列表失败',
		      icon: 'none'
		    });
		  }
	},
    
    // 显示更多选项
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['刷新', '设置', '帮助'],
        success: (res) => {
          console.log('选择了第' + (res.tapIndex + 1) + '个选项')
        }
      })
    },
    
    // 最小化
    minimize() {
      console.log('最小化')
    },
    
    // 显示目标
    showTarget() {
      console.log('显示目标')
    },
    
    // 初始化页面数据
    async initPageData(options) {
      console.log('订单提交页面接收参数:', options);
      
      // 根据传入参数初始化数据
      if (options.productId) {
        // 从URL参数获取商品信息
        this.loadProductInfoFromParams(options);
      }
      
      // 获取地址信息（优先使用传入的addressId，否则使用默认地址）
      if (options.addressId) {
        await this.loadAddressInfo(options.addressId);
      } else {
        // 如果没有传入地址ID，尝试获取用户默认地址
        await this.loadDefaultAddress();
      }
      
      // 如果没有商品ID参数，尝试从现有数据加载
      if (!options.productId) {
        this.find();
      }
    },
    
    // 从URL参数加载商品信息
    loadProductInfoFromParams(options) {
      try {
        console.log('从URL参数加载商品信息:', options);
        
        // 更新商品信息
        this.productInfo = {
          ...this.productInfo,
          name: options.productName || '商品名称',
          image: options.productImage || '/static/logo.png',
          specs: options.productSpecs || '',
          quantity: parseInt(options.productQuantity) || 1,
          price: options.productPrice || '0.00'
        };
        
        // 更新配送费用
        this.deliveryFee = (parseFloat(options.shipping) || 0).toFixed(2);
        
        // 计算商品总价
        this.totalProductPrice = (parseFloat(this.productInfo.price) * this.productInfo.quantity).toFixed(2);
        this.totalQuantity = this.productInfo.quantity;
        
        // 计算总金额
        this.calculateTotal();
        
        // 保存商品参数到订单数据
        this.orderData = {
          productId: options.productId,
          productName: options.productName,
          productImage: options.productImage,
          productPrice: options.productPrice,
          productSpecs: options.productSpecs,
          productQuantity: options.productQuantity,
          productSkuId: options.productSkuId,
          businessId: options.businessId,
          shipping: options.shipping
        };
        
        console.log('商品信息加载完成:', this.productInfo);
        console.log('订单数据:', this.orderData);
        
      } catch (error) {
        console.error('从URL参数加载商品信息失败:', error);
        // 如果加载失败，回退到原有逻辑
        this.find();
      }
    },
    
    // 加载商品信息
    loadProductInfo(productId) {
      // 模拟API调用
      console.log('加载商品信息:', productId)
    },
    
    // 加载地址信息
    async loadAddressInfo(addressId) {
      try {
        console.log('加载地址信息:', addressId);
        
        // 调用地址API工具函数获取地址信息
        const response = await getAddressById(addressId);
        
        if (response && response.code === 200 && response.data) {
          const addressData = response.data;
          
          // 更新地址信息，使用后端UserAddress实体类字段
          this.addressInfo = {
            id: addressData.id,
            province: addressData.province,
            city: addressData.city,
            county: addressData.county,
            content: addressData.content,
            username: addressData.userName, // 注意：后端是userName，前端是username
            phone: addressData.phone,
            address: formatAddress(addressData) // 使用格式化函数
          };
          
          console.log('地址信息加载成功:', this.addressInfo);
        } else {
          console.warn('地址信息加载失败，使用默认地址');
          this.loadDefaultAddress();
        }
      } catch (error) {
        console.error('加载地址信息失败:', error);
        this.loadDefaultAddress();
      }
    },
    
    // 加载默认地址
    async loadDefaultAddress() {
      try {
        // 如果有用户ID，尝试获取用户的地址列表
        if (this.userId) {
          const response = await get('/address/list', { userId: this.userId });
          
          if (response && response.code === 200 && response.rows && response.rows.length > 0) {
            // 优先查找标记为默认的地址，如果没有则使用第一个地址
            let defaultAddress = response.rows.find(addr => addr.isDefault === true) || response.rows[0];
            
            this.addressInfo = {
              id: defaultAddress.id,
              province: defaultAddress.province,
              city: defaultAddress.city,
              county: defaultAddress.county,
              content: defaultAddress.content,
              username: defaultAddress.userName,
              phone: defaultAddress.phone,
              address: `${defaultAddress.province || ''}${defaultAddress.city || ''}${defaultAddress.county || ''}${defaultAddress.content || ''}`
            };
            
            console.log('加载用户默认地址:', this.addressInfo);
            return;
          }
        }
        
        // 如果没有用户地址，使用静态默认地址
        const staticDefaultAddress = getDefaultAddress();
        
        this.addressInfo = {
          id: staticDefaultAddress.id,
          province: staticDefaultAddress.province,
          city: staticDefaultAddress.city,
          county: staticDefaultAddress.county,
          content: staticDefaultAddress.content,
          username: staticDefaultAddress.userName,
          phone: staticDefaultAddress.phone,
          address: formatAddress(staticDefaultAddress)
        };
        
        console.log('加载静态默认地址:', this.addressInfo);
      } catch (error) {
        console.error('加载默认地址失败:', error);
        
        // 如果加载失败，使用静态默认地址
        const staticDefaultAddress = getDefaultAddress();
        
        this.addressInfo = {
          id: staticDefaultAddress.id,
          province: staticDefaultAddress.province,
          city: staticDefaultAddress.city,
          county: staticDefaultAddress.county,
          content: staticDefaultAddress.content,
          username: staticDefaultAddress.userName,
          phone: staticDefaultAddress.phone,
          address: formatAddress(staticDefaultAddress)
        };
        
        console.log('加载静态默认地址:', this.addressInfo);
      }
    },
    
    // 选择地址
    selectAddress() {
      // 先检查是否有用户ID
      if (!this.userId) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        });
        return;
      }
      
      // 跳转到地址选择页面，并传递来源标识
      uni.navigateTo({
        url: '/pages/address/address?from=order',
        events: {
          // 监听地址选择结果
          addressSelected: (addressData) => {
            console.log('选择的地址:', addressData);
            // 更新地址信息
            this.addressInfo = {
              id: addressData.id,
              province: addressData.province,
              city: addressData.city,
              county: addressData.district,
              content: addressData.detailAddress,
              username: addressData.name,
              phone: addressData.phone,
              address: `${addressData.province || ''}${addressData.city || ''}${addressData.district || ''}${addressData.detailAddress || ''}`
            };
            
            console.log('地址信息已更新:', this.addressInfo);
            
            uni.showToast({
              title: '地址选择成功',
              icon: 'success'
            });
          }
        },
        success: () => {
          console.log('跳转到地址选择页面');
        },
        fail: (err) => {
          console.error('跳转地址选择页面失败:', err);
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    },
    
    // 加载用户地址列表
    async loadUserAddressList() {
      try {
        console.log('加载用户地址列表，用户ID:', this.userId);
        
        // 调用地址API获取用户地址列表，将userId作为查询参数传递给UserAddress对象
        const response = await get('/address/list', { userId: this.userId });
        
        if (response && response.code === 200 && response.rows && response.rows.length > 0) {
          // 显示地址选择弹窗
          this.showAddressSelector(response.rows);
        } else {
          // 如果没有地址，提示添加地址
          uni.showModal({
            title: '提示',
            content: '您还没有添加收货地址，是否现在添加？',
            success: (res) => {
              if (res.confirm) {
                // 跳转到添加地址页面
                uni.navigateTo({
                  url: '/pages/add-address/add-address'
                });
              }
            }
          });
        }
      } catch (error) {
        console.error('加载地址列表失败:', error);
        uni.showToast({
          title: '加载地址失败',
          icon: 'none'
        });
      }
    },
    
    // 显示地址选择器
    showAddressSelector(addressList) {
      // 构建地址选项列表
      const addressOptions = addressList.map((address, index) => {
        const addressText = `${address.province || ''}${address.city || ''}${address.county || ''}${address.content || ''}`;
        return {
          label: `${address.userName || '用户'} ${address.phone || ''}\n${addressText}`,
          value: index,
          address: address
        };
      });
      
      // 显示地址选择弹窗
      uni.showActionSheet({
        itemList: addressOptions.map(item => item.label),
        success: (res) => {
          const selectedIndex = res.tapIndex;
          const selectedAddress = addressOptions[selectedIndex].address;
          
          console.log('选择的地址:', selectedAddress);
          
          // 更新地址信息
          this.addressInfo = {
            id: selectedAddress.id,
            province: selectedAddress.province,
            city: selectedAddress.city,
            county: selectedAddress.county,
            content: selectedAddress.content,
            username: selectedAddress.userName,
            phone: selectedAddress.phone,
            address: `${selectedAddress.province || ''}${selectedAddress.city || ''}${selectedAddress.county || ''}${selectedAddress.content || ''}`
          };
          
          console.log('地址信息已更新:', this.addressInfo);
          
          uni.showToast({
            title: '地址选择成功',
            icon: 'success'
          });
        }
      });
    },
    
    // 刷新地址信息
    async refreshAddressInfo() {
      try {
        // 如果有用户ID，重新加载地址信息
        if (this.userId) {
          await this.loadDefaultAddress();
        }
      } catch (error) {
        console.error('刷新地址信息失败:', error);
      }
    },
    
    // 监听地址变化事件
    onAddressChanged() {
      // 当地址发生变化时，刷新地址信息
      this.refreshAddressInfo();
    },
    
    // 选择配送服务
    selectDeliveryService() {
      uni.showActionSheet({
        itemList: ['快递配送', '到店自提', '同城配送'],
        success: (res) => {
          const services = ['快递配送', '到店自提', '同城配送']
          this.deliveryService = services[res.tapIndex]
          this.calculateTotal()
        }
      })
    },
    
    // 选择店铺优惠券
    selectStoreCoupon() {
      uni.navigateTo({
        url: '/pages/coupon/coupon?select=true'
      })
    },
    
    // 添加订单备注
    addOrderNote() {
      uni.showModal({
        title: '订单备注',
        editable: true,
        placeholderText: '请输入订单备注',
        content: this.orderNote,
        success: (res) => {
          if (res.confirm) {
            this.orderNote = res.content
          }
        }
      })
    },
    
    // 选择发票
    selectInvoice() {
      uni.showActionSheet({
        itemList: ['本次不开具发票', '开具普通发票', '开具专用发票'],
        success: (res) => {
          const invoices = ['本次不开具发票', '开具普通发票', '开具专用发票']
          this.invoiceText = invoices[res.tapIndex]
        }
      })
    },
    
    // 切换积分抵扣
    togglePoints(value) {
      this.usePoints = value
      this.calculateTotal()
    },
    
    // 计算总价
    calculateTotal() {
      let total = parseFloat(this.totalProductPrice)
      
      // 减去店铺优惠券
      total -= parseFloat(this.storeCoupon)
      
      // 减去平台优惠券
      total -= parseFloat(this.platformCoupon)
      
      // 加上配送费
      total += parseFloat(this.deliveryFee)
      
      // 积分抵扣（如果有的话）
      if (this.usePoints) {
        // 这里可以添加积分抵扣逻辑
        total -= 0 // 暂时设为0
      }
      
      this.totalAmount = total.toFixed(2)
      this.totalDiscount = (parseFloat(this.totalProductPrice) - total).toFixed(2)
    },
    
    // 提交订单
    submitOrder() {
      if (!this.addressInfo.address) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      this.submitting = true
      
      // 如果有从商品详情页传递的数据，使用这些数据创建订单
      if (this.orderData && this.orderData.productId) {
        this.createOrderFromProductData();
      } else {
        // 否则使用原有逻辑
        this.submitOrderWithExistingData();
      }
    },
    
    // 使用商品详情页数据创建订单
    async createOrderFromProductData() {
      try {
        console.log('使用商品详情页数据创建订单:', this.orderData);
        
        // 构建订单数据，严格按照后端Order实体类字段映射
        const orderData = {
          // 核心订单字段
          userId: this.userId || 1, // 用户ID，默认1
          goodsId: parseInt(this.orderData.productId), // 商品ID
          businessId: parseInt(this.orderData.businessId) || 1, // 商家ID
          goodsSpecs: this.orderData.productSpecs || '默认规格', // 商品规格信息
          orderPrice: parseFloat(this.orderData.productPrice), // 支付价格
          orderCreateTime: new Date(), // 订单创建时间
          orderStatus: 0, // 订单状态(0-待支付,1-已支付,2-已发货,3-已完成,4-已取消)
          orderComment: this.orderNote || '', // 订单备注
          orderNumber: this.generateOrderNumber(), // 订单单号
          orderPostPrice: parseFloat(this.orderData.shipping || 0), // 运费
          orderType: 0, // 订单是否删除(0-未删除,1-已删除)
          addressId: this.addressInfo.id || 1, // 使用真实地址ID
          
          // 扩展字段（用于显示和查询）
          goodsname: this.orderData.productName, // 商品名称
          goodsprice: this.orderData.productPrice, // 商品价格
          goodsnumber: this.orderData.productQuantity.toString(), // 商品数量
          goodsimg: this.orderData.productImage, // 商品图片
          goodsVirtual: 0, // 商品类型(0-实物商品,1-虚拟商品)
          username: this.addressInfo.username || '用户', // 用户名
          userphone: this.addressInfo.phone || '', // 用户电话
          useraddress: this.addressInfo.address || '' // 用户地址
        };
        
        console.log('准备创建的订单数据:', orderData);
        
        // 调用后端API创建订单
        const response = await this.createOrder(orderData);
        
        if (response && response.code === 200) {
          this.submitting = false;
          uni.showToast({
            title: '订单创建成功',
            icon: 'success'
          });
          
          // 订单创建成功后，跳转到订单列表页面
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages/order/order-list'
            });
          }, 1500);
          
        } else {
          throw new Error(response?.msg || '创建订单失败');
        }
        
      } catch (error) {
        this.submitting = false;
        console.error('创建订单失败:', error);
        uni.showToast({
          title: error.message || '创建订单失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 使用原有数据提交订单
    submitOrderWithExistingData() {
      // 模拟提交订单
      setTimeout(() => {
        this.submitting = false
        
        uni.showModal({
          title: '订单提交成功',
          content: '您的订单已提交，请及时付款',
          showCancel: false,
          success: () => {
            // 跳转到支付页面或订单列表
            uni.navigateTo({
              url: '/pages/orderlist/orderlist'
            })
          }
        })
      }, 2000)
    },
    
    // 生成订单号
    generateOrderNumber() {
      const timestamp = Date.now();
      const random = Math.floor(Math.random() * 1000);
      return `ORDER${timestamp}${random}`;
    },
    
    // 调用后端API创建订单
    async createOrder(orderData) {
      try {
        console.log('发送订单数据到后端:', orderData);
        
        // 使用导入的put方法调用后端API
        const res = await put('/zmhshop/orderst', { data: orderData });
        
        console.log('创建订单API响应:', res);
        
        if (res && res.code === 200) {
          return res;
        } else {
          throw new Error(res?.msg || '创建订单失败');
        }
      } catch (error) {
        console.error('创建订单API请求失败:', error);
        throw new Error('网络请求失败，请检查网络连接');
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.submitorder-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.custom-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .navbar-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .navbar-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
  }
  
  .navbar-right {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .u-icon {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.address-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .address-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .address-left {
      display: flex;
      align-items: flex-start;
      gap: 20rpx;
      flex: 1;
      
      .address-info {
        .address-text {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          margin-bottom: 10rpx;
          line-height: 1.4;
        }
        
        .phone-text {
          font-size: 28rpx;
          color: #999999;
        }
      }
    }
    
    .address-right {
      width: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.product-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .shop-info {
    display: flex;
    align-items: center;
    gap: 10rpx;
    margin-bottom: 20rpx;
    
    .shop-name {
      font-size: 28rpx;
      color: #333333;
    }
  }
  
  .product-item {
    display: flex;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      background-color: #f5f5f5;
    }
    
    .product-info {
      flex: 1;
      
      .product-name {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
        line-height: 1.4;
      }
      
      .product-specs {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 10rpx;
      }
      
      .product-quantity {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 15rpx;
      }
      
      .product-price {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
      }
    }
  }
  
  .order-options {
    .option-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .option-label {
        font-size: 28rpx;
        color: #333333;
      }
      
      .option-right {
        display: flex;
        align-items: center;
        gap: 10rpx;
        
        .option-value {
          font-size: 28rpx;
          color: #666666;
          
          &.coupon-value {
            color: #ff4444;
          }
        }
      }
    }
  }
}

.price-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .price-label {
      font-size: 28rpx;
      color: #333333;
    }
    
    .price-right {
      display: flex;
      align-items: center;
      gap: 10rpx;
      
      .price-value {
        font-size: 28rpx;
        color: #333333;
        
        &.coupon-value {
          color: #ff4444;
        }
      }
      
      .points-text {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
}

.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .footer-left {
    .total-info {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 5rpx;
      
      .total-price {
        font-size: 36rpx;
        font-weight: 600;
        color: #ff4444;
      }
    }
    
    .discount-info {
      font-size: 24rpx;
      color: #ff4444;
    }
  }
  
  .footer-right {
    .u-button {
      width: 200rpx;
      height: 80rpx;
      border-radius: 40rpx;
      background-color: #ff4444;
      border: none;
      
      &::after {
        border: none;
      }
    }
  }
}
</style> -->
<template>
  <view class="submitorder-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-left" @click="goBack">
        <u-icon name="arrow-left" size="20" color="#333"></u-icon>
      </view>
      <view class="navbar-title">提交订单</view>
      <view class="navbar-right">
        <u-icon name="more-dot-fill" size="20" color="#333" @click="showMoreOptions"></u-icon>
        <u-icon name="minus" size="20" color="#333" @click="minimize"></u-icon>
        <u-icon name="target" size="20" color="#333" @click="showTarget"></u-icon>
      </view>
    </view>

    <!-- 地址选择 -->
    <view class="address-section" @click="selectAddress">
      <view class="address-content">
        <view class="address-left">
          <u-icon name="map-pin" size="24" color="#ff4444"></u-icon>
          <view class="address-info">
            <view class="address-text">{{addressInfo.username}} {{addressInfo.address}}</view>
            <view class="phone-text">{{addressInfo.phone}}</view>
          </view>
        </view>
        <view class="address-right">
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="product-section">
      <view class="shop-info">
        <u-icon name="shopping-cart" size="16" color="#333"></u-icon>
        <text class="shop-name">{{productInfo.shopName}}</text>
      </view>
      
      <view class="product-item">
        <image class="product-image" :src="productInfo.image" mode="aspectFill"></image>
        <view class="product-info">
          <view class="product-name">{{productInfo.name}}</view>
          <view class="product-specs" v-if="productInfo.specs">{{productInfo.specs}}</view>
          <view class="product-quantity">数量:{{productInfo.quantity}}</view>
          <view class="product-price">¥ {{productInfo.price}}</view>
        </view>
      </view>
      
      <!-- 订单选项 -->
      <view class="order-options">
        <view class="option-item" @click="selectDeliveryService">
          <text class="option-label">配送服务</text>
          <view class="option-right">
            <text class="option-value">{{deliveryService}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item">
          <text class="option-label">配送费用</text>
          <view class="option-right">
            <text class="option-value">¥ {{deliveryFee}}</text>
          </view>
        </view>
        
        <view class="option-item" @click="selectStoreCoupon">
          <text class="option-label">店铺优惠券</text>
          <view class="option-right">
            <text class="option-value coupon-value">- ¥ {{storeCoupon}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item" @click="addOrderNote">
          <text class="option-label">订单备注</text>
          <view class="option-right">
            <text class="option-value">{{orderNote || '选填'}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
        
        <view class="option-item" @click="selectInvoice">
          <text class="option-label">开具发票</text>
          <view class="option-right">
            <text class="option-value">{{invoiceText}}</text>
            <u-icon name="arrow-right" size="16" color="#999"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格明细 -->
    <view class="price-section">
      <view class="section-title">价格明细</view>
      
      <view class="price-item">
        <text class="price-label">平台优惠券</text>
        <view class="price-right">
          <text class="price-value coupon-value">-¥{{platformCoupon}}</text>
          <u-icon name="arrow-right" size="16" color="#999"></u-icon>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">积分抵扣</text>
        <view class="price-right">
          <u-checkbox 
            v-model="usePoints" 
            @change="togglePoints"
            shape="circle"
            size="20"
          ></u-checkbox>
          <text class="points-text">{{usePoints ? '使用积分抵扣' : '不使用积分抵扣'}}</text>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">商品总价</text>
        <view class="price-right">
          <text class="price-value">¥{{totalProductPrice}}</text>
        </view>
      </view>
      
      <view class="price-item">
        <text class="price-label">店铺优惠</text>
        <view class="price-right">
          <text class="price-value coupon-value">-¥{{storeDiscount}}</text>
        </view>
      </view>
    </view>

    <!-- 底部提交栏 -->
    <view class="footer-bar">
      <view class="footer-left">
        <view class="total-info">
          共{{totalQuantity}}件 合计:¥<text class="total-price">{{totalAmount}}</text>
        </view>
        <view class="discount-info">共优惠 ¥{{totalDiscount}}元</view>
      </view>
      <view class="footer-right">
        <u-button 
          type="primary" 
          size="large" 
          @click="submitOrder"
          :loading="submitting"
        >提交订单</u-button>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserId } from '../../utils/auth.js';
import { get, post, del, put } from '../../utils/request.js';
import { getAddressById, getDefaultAddress, formatAddress } from '../../utils/addressApi.js';

export default {
  name: 'SubmitOrder',
  data() {
    return {
      submitting: false,
      usePoints: false,
      addressInfo: {
        address: '',
        phone: '',
        username: ''
      },
      productInfo: {
        shopName: 'Mall4j蓝海商城',
        name: '',
        quantity: 0,
        price: '0.00',
        image: '',
        specs: ''
      },
      deliveryService: '快递配送',
      deliveryFee: '0.00',
      storeCoupon: '0.00',
      orderNote: '',
      invoiceText: '本次不开具发票',
      platformCoupon: '0.00',
      totalProductPrice: '0.00',
      storeDiscount: '0.00',
      totalQuantity: 0,
      totalAmount: '0.00',
      totalDiscount: '0.00',
      userId: Number(getUserId()),
      orderData: null
    }
  },
  async onLoad(options) {
    console.log('订单提交页面加载，接收参数:', options);
    
    try {
      await this.initPageData(options);
      
      if (!options.productId) {
        this.find();
      }
    } catch (error) {
      console.error('页面初始化失败:', error);
      this.loadDefaultAddress();
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    goToLogin() {
      uni.navigateTo({
        url: '/pages/login/login'
      });
    },

    async find() {
      try {
        const res = await get('/orderst/list',{});
        if (res && res.code === 200) {
          let orderData = res.data || res.rows || [];
          
          if (Array.isArray(orderData) && orderData.length > 0) {
            let submitorder = orderData[0];
            
            this.addressInfo.address = submitorder.useraddress || '';
            this.addressInfo.username = submitorder.username || '';
            this.addressInfo.phone = submitorder.userphone || '';
            
            this.productInfo.name = submitorder.goodsname || '';
            this.productInfo.image = submitorder.goodsimg || '';
            this.productInfo.specs = submitorder.goodsSpecs || '';
            this.productInfo.quantity = parseInt(submitorder.goodsnumber) || 0;
            this.productInfo.price = submitorder.goodsprice || '0.00';
            
            this.orderNote = submitorder.orderComment || '';
            this.totalProductPrice = (parseFloat(submitorder.goodsprice || 0) * parseInt(submitorder.goodsnumber || 0)).toFixed(2);
            this.deliveryFee = (parseFloat(submitorder.orderPostPrice || 0)).toFixed(2);
            this.totalQuantity = parseInt(submitorder.goodsnumber) || 0;
            
            this.calculateTotal();
            
            this.orderData = submitorder;
          } else {
            this.loadDefaultAddress();
          }
        }
      } catch (error) {
        console.error('获取订单列表失败:', error);
        uni.showToast({
          title: '获取订单列表失败',
          icon: 'none'
        });
      }
    },
    
    showMoreOptions() {
      uni.showActionSheet({
        itemList: ['刷新', '设置', '帮助'],
        success: (res) => {
          console.log('选择了第' + (res.tapIndex + 1) + '个选项')
        }
      })
    },
    
    minimize() {
      console.log('最小化')
    },
    
    showTarget() {
      console.log('显示目标')
    },
    
    async initPageData(options) {
      console.log('订单提交页面接收参数:', options);
      
      if (options.productId) {
        this.loadProductInfoFromParams(options);
      }
      
      if (options.addressId) {
        await this.loadAddressInfo(options.addressId);
      } else {
        await this.loadDefaultAddress();
      }
      
      if (!options.productId) {
        this.find();
      }
    },
    
    loadProductInfoFromParams(options) {
      try {
        this.productInfo = {
          ...this.productInfo,
          name: options.productName || '商品名称',
          image: options.productImage || '/static/logo.png',
          specs: options.productSpecs || '',
          quantity: parseInt(options.productQuantity) || 1,
          price: options.productPrice || '0.00'
        };
        
        this.deliveryFee = (parseFloat(options.shipping) || 0).toFixed(2);
        
        this.totalProductPrice = (parseFloat(this.productInfo.price) * this.productInfo.quantity).toFixed(2);
        this.totalQuantity = this.productInfo.quantity;
        
        this.calculateTotal();
        
        this.orderData = {
          productId: options.productId,
          productName: options.productName,
          productImage: options.productImage,
          productPrice: options.productPrice,
          productSpecs: options.productSpecs,
          productQuantity: options.productQuantity,
          productSkuId: options.productSkuId,
          businessId: options.businessId,
          shipping: options.shipping
        };
      } catch (error) {
        console.error('从URL参数加载商品信息失败:', error);
        this.find();
      }
    },
    
    async loadAddressInfo(addressId) {
      try {
        const response = await getAddressById(addressId);
        
        if (response && response.code === 200 && response.data) {
          const addressData = response.data;
          
          this.addressInfo = {
            id: addressData.id,
            province: addressData.province,
            city: addressData.city,
            county: addressData.county,
            content: addressData.content,
            username: addressData.userName,
            phone: addressData.phone,
            address: formatAddress(addressData)
          };
        } else {
          this.loadDefaultAddress();
        }
      } catch (error) {
        console.error('加载地址信息失败:', error);
        this.loadDefaultAddress();
      }
    },
    
    loadDefaultAddress() {
      const defaultAddress = getDefaultAddress();
      
      this.addressInfo = {
        id: defaultAddress.id,
        province: defaultAddress.province,
        city: defaultAddress.city,
        county: defaultAddress.county,
        content: defaultAddress.content,
        username: defaultAddress.userName,
        phone: defaultAddress.phone,
        address: formatAddress(defaultAddress)
      };
    },
    
    selectAddress() {
      uni.navigateTo({
        url: '/pages/address/address?select=true',
        events: {
          addressSelected: (addressData) => {
            this.addressInfo = {
              id: addressData.id,
              province: addressData.province,
              city: addressData.city,
              county: addressData.county,
              content: addressData.content,
              username: addressData.userName,
              phone: addressData.phone,
              address: `${addressData.province}${addressData.city}${addressData.county}${addressData.content}`
            };
          }
        },
        success: () => {
          console.log('跳转到地址选择页面');
        },
        fail: (err) => {
          console.error('跳转地址选择页面失败:', err);
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    },
    
    selectDeliveryService() {
      uni.showActionSheet({
        itemList: ['快递配送', '到店自提', '同城配送'],
        success: (res) => {
          const services = ['快递配送', '到店自提', '同城配送']
          this.deliveryService = services[res.tapIndex]
          this.calculateTotal()
        }
      })
    },
    
    selectStoreCoupon() {
      uni.navigateTo({
        url: '/pages/coupon/coupon?select=true'
      })
    },
    
    addOrderNote() {
      uni.showModal({
        title: '订单备注',
        editable: true,
        placeholderText: '请输入订单备注',
        content: this.orderNote,
        success: (res) => {
          if (res.confirm) {
            this.orderNote = res.content
          }
        }
      })
    },
    
    selectInvoice() {
      uni.showActionSheet({
        itemList: ['本次不开具发票', '开具普通发票', '开具专用发票'],
        success: (res) => {
          const invoices = ['本次不开具发票', '开具普通发票', '开具专用发票']
          this.invoiceText = invoices[res.tapIndex]
        }
      })
    },
    
    togglePoints(value) {
      this.usePoints = value
      this.calculateTotal()
    },
    
    calculateTotal() {
      let total = parseFloat(this.totalProductPrice)
      
      total -= parseFloat(this.storeCoupon)
      total -= parseFloat(this.platformCoupon)
      total += parseFloat(this.deliveryFee)
      
      if (this.usePoints) {
        total -= 0
      }
      
      this.totalAmount = total.toFixed(2)
      this.totalDiscount = (parseFloat(this.totalProductPrice) - total).toFixed(2)
    },
    
    async submitOrder() {
      if (!this.addressInfo.address) {
        uni.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }
      
      this.submitting = true
      
      try {
        // 构造要传递的订单数据
        const orderData = {
          userId: this.userId,
          goodsName: this.productInfo.name,
          goodsPrice: this.productInfo.price,
          goodsQuantity: this.productInfo.quantity,
          goodsImage: this.productInfo.image,
          goodsSpecs: this.productInfo.specs,
          totalAmount: this.totalAmount,
          deliveryFee: this.deliveryFee,
          addressInfo: this.addressInfo,
          orderNote: this.orderNote,
          deliveryService: this.deliveryService
        };
        
        // 编码为URL参数
        const queryParams = Object.keys(orderData)
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(JSON.stringify(orderData[key]))}`)
          .join('&');
        
        // 跳转到订单列表页并传递数据
        uni.navigateTo({
          url: `/pages/order/order-list?fromSubmit=1&${queryParams}`
        });
        
      } catch (error) {
        console.error('提交订单失败:', error);
        uni.showToast({
          title: '提交订单失败',
          icon: 'none'
        });
      } finally {
        this.submitting = false;
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.submitorder-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
}

.custom-navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .navbar-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .navbar-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #333333;
  }
  
  .navbar-right {
    display: flex;
    align-items: center;
    gap: 20rpx;
    
    .u-icon {
      width: 60rpx;
      height: 60rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.address-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .address-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .address-left {
      display: flex;
      align-items: flex-start;
      gap: 20rpx;
      flex: 1;
      
      .address-info {
        .address-text {
          font-size: 32rpx;
          font-weight: 600;
          color: #333333;
          margin-bottom: 10rpx;
          line-height: 1.4;
        }
        
        .phone-text {
          font-size: 28rpx;
          color: #999999;
        }
      }
    }
    
    .address-right {
      width: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.product-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .shop-info {
    display: flex;
    align-items: center;
    gap: 10rpx;
    margin-bottom: 20rpx;
    
    .shop-name {
      font-size: 28rpx;
      color: #333333;
    }
  }
  
  .product-item {
    display: flex;
    gap: 20rpx;
    margin-bottom: 30rpx;
    
    .product-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 10rpx;
      background-color: #f5f5f5;
    }
    
    .product-info {
      flex: 1;
      
      .product-name {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
        line-height: 1.4;
      }
      
      .product-specs {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 10rpx;
      }
      
      .product-quantity {
        font-size: 24rpx;
        color: #999999;
        margin-bottom: 15rpx;
      }
      
      .product-price {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
      }
    }
  }
  
  .order-options {
    .option-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .option-label {
        font-size: 28rpx;
        color: #333333;
      }
      
      .option-right {
        display: flex;
        align-items: center;
        gap: 10rpx;
        
        .option-value {
          font-size: 28rpx;
          color: #666666;
          
          &.coupon-value {
            color: #ff4444;
          }
        }
      }
    }
  }
}

.price-section {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    margin-bottom: 20rpx;
  }
  
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .price-label {
      font-size: 28rpx;
      color: #333333;
    }
    
    .price-right {
      display: flex;
      align-items: center;
      gap: 10rpx;
      
      .price-value {
        font-size: 28rpx;
        color: #333333;
        
        &.coupon-value {
          color: #ff4444;
        }
      }
      
      .points-text {
        font-size: 28rpx;
        color: #666666;
      }
    }
  }
}

.footer-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .footer-left {
    .total-info {
      font-size: 28rpx;
      color: #333333;
      margin-bottom: 5rpx;
      
      .total-price {
        font-size: 36rpx;
        font-weight: 600;
        color: #ff4444;
      }
    }
    
    .discount-info {
      font-size: 24rpx;
      color: #ff4444;
    }
  }
  
  .footer-right {
    .u-button {
      width: 200rpx;
      height: 80rpx;
      border-radius: 40rpx;
      background-color: #ff4444;
      border: none;
      
      &::after {
        border: none;
      }
    }
  }
}
</style>